package com.yonyou.ucf.mdf.app.isvdxq.secondpart.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PurOut;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.PutInStock;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpclistService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpcotherService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpcpickService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.StorerecordService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/epcpick",DxqConfig.pre_pcUrl+"/epcpick"})
public class EpcpickController {
    private static final Logger logger = LoggerFactory.getLogger(EpcpickController.class);

    @Autowired
    BaseService baseService;
    @Autowired
    private EpcpickService epcpickService;
    @Autowired
    private EpclistService epclistService;
    @Autowired
    private StorerecordService storerecordService;
    @Autowired
    private OrderNoticeService orderNoticeService;

    //删除拣货
    @RequestMapping("/EpcpickDel")
    public DataResult EpcpickDel(String id, String rfidcodeId, String modifier, HttpServletRequest request) throws Exception {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            return epcpickService.EpcpickDel(id, rfidcodeId, modifier, tenantId);
        } catch (Exception ex) {
            String logtxt = "[DelJianhuo]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    /**
     * 拣货 [物料拣货/按单拣货]
     * 服务端不检测是否拣货完成
     *
     * @param tenant_id
     * @param PurOutList
     * @return
     */
    @PostMapping("/EpcpickSubmit")
    public DataResult EpcpickSubmit(String tenant_id, @RequestBody List<PurOut> PurOutList) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            result = epcpickService.EpcpickSubmit(PurOutList, tenant_id);
        } catch (Exception ex) {
            String logtxt = "[FahuoRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    /**
     * 手机端拉取到货单据列表 用友到货发签 分批次发签
     * 根据单子主键， 详情表主键绑定标签 [===发签入库]
     * 到货发签 - （唯一码）提交用友入库 - 回写本地
     *
     * @param tenant_id
     * @param CodeBindList
     * @param request
     * @return
     */
    @PostMapping("/BindEpcSubmit")
    public DataResult BindEpcSubmit(String tenant_id, @RequestBody List<RfidCodebind> CodeBindList, HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            List<String> epcs = CodeBindList.stream().map(it -> it.getRfid_code())
                    .distinct().collect(Collectors.toList());
            List<EpcEntity> list_epcEntity = epclistService.SelectByEpcs(epcs, tenant_id);
            boolean flagEpcUsed = EpcotherService.CheckEpcUsed(list_epcEntity);
            if (flagEpcUsed) {
                result.setMessage("标签已占用");
                return result;
            }
            result = epcpickService.BindEpcSubmit(CodeBindList);
        } catch (Exception ex) {
            String logtxt = "[SubmitBindReRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    //根据单子主键， 详情表主键解绑标签 默认到货发签解绑
    @RequestMapping("/BindEpcDel")
    public DataResult BindEpcDel(String tenant_id, String rfidcodeId, String modifier, String ordertype) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            List<String> ids_recordList = new ArrayList<>();
            List<String> ids_rfidList = new ArrayList<>();
            if (rfidcodeId.length() > 0) {
                String[] strings = rfidcodeId.split(",");
                ids_rfidList.addAll(Arrays.asList(strings));
            }
            ordertype = StringUtils.isEmpty(ordertype) ? "3" : ordertype;
            List<StorerecordEntity> list_record = storerecordService.selectStorerecordByEpcIds(ids_rfidList, ordertype,
                    tenant_id);
            //验证单据解绑
            long checkNum = list_record.stream().filter(it -> StringUtils.isNotEmpty(it.getBatch_no())).count();
            if (checkNum > 0) {
                result = new DataResult(0, "要删除的物料标签已部分到货提交,不允许删除！");
                return result;
            }
            ids_recordList = list_record.stream()
                    .filter(it -> it.getOrdertype().equals("3")) //过滤到货单
                    .map(it -> it.getId()).distinct().collect(Collectors.toList());
            String id = String.join(",", ids_recordList);
            return epcpickService.BindEpcDel(id, rfidcodeId, modifier, tenant_id, false);
        } catch (Exception ex) {
            String logtxt = "[SubmitBindReRFIDCode]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    //手持机推送接口到用友，用友会写本地数据 [===入库回写]
    @RequestMapping("/InStockParamsCallback")
    public DataResult InStockParamsCallback(HttpServletRequest request, @RequestBody Map<String, Object> paramData) throws Exception {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        Map<String, Object> myParms = RequestTool.getParams(request);
        String batch_no = (String) myParms.get("batch_no");
        List<String> epcids = (List<String>) paramData.get("epcids");
        List<PutInStock> putinstocklist = (List<PutInStock>) paramData.get("putinstocklist");
        result = epcpickService.InStockParamsCallback(putinstocklist, epcids, null, tenantId, batch_no);
        if (result.getStatus() != 1) {
            try {
                String modifier = putinstocklist.get(0).getModifier();
                String orderid = putinstocklist.get(0).getSourceid();
                String orderdetailid = putinstocklist.get(0).getOrderdetailid();
                String modelString = JSONObject.toJSONString(putinstocklist);
                OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                recordEntity.setTenant_id(tenantId);
                recordEntity.setOrderid(orderid);
                recordEntity.setOrderdetailids(orderdetailid);
                recordEntity.setActioncode("callback");
                recordEntity.setPickbatchno("");
                recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                recordEntity.setRemarkyonyou(modelString);
                recordEntity.setRemarkdxq("");
                recordEntity.setRemark(result.getMessage());
                recordEntity.setModifier(modifier);
                recordEntity.setStatus(result.getStatus());
                orderNoticeService.InsertEntity(recordEntity);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            result.setMessage("本地回写失败");
            result.setStatus(1);
        }
        return result;
    }


    /**
     * 本地出库提交
     * 更新拣货信息为出库 [用友先出==出库回写]
     *
     * @param request    orderid\orderdetailid\pickbatchno
     * @param PurOutList
     * @return
     * @throws Exception
     */
    @RequestMapping("/OutStatusCallback")
    public DataResult OutStatusCallback(HttpServletRequest request, @RequestBody List<PurOut> PurOutList) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String orderid = (String) reqParams.get("orderid");
            String orderdetailid = (String) reqParams.get("orderdetailid");
            String pickbatchno = (String) reqParams.get("pickbatchno"); //配货批次
            if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(pickbatchno)) {
                result.setMessage("参数异常");
                return result;
            }
            result = epcpickService.OutStatusCallback(PurOutList, orderid, pickbatchno, tenantId, userId);
            if (result.getStatus() != 1) {
                orderNoticeService.EditEntityStatusForPick(orderid, DxqConfig.AllotOk, 1, DxqConfig.StatusFail, userId, pickbatchno, tenantId);
                try {
                    String modelString = JSONObject.toJSONString(PurOutList);
                    OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                    recordEntity.setTenant_id(tenantId);
                    recordEntity.setOrderid(orderid);
                    recordEntity.setOrderdetailids(orderdetailid);
                    recordEntity.setActioncode("callback");
                    recordEntity.setPickbatchno(pickbatchno);
                    recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                    recordEntity.setRemarkyonyou(modelString);
                    recordEntity.setRemarkdxq("");
                    recordEntity.setRemark(result.getMessage());
                    recordEntity.setModifier(userId);
                    recordEntity.setStatus(result.getStatus());
                    orderNoticeService.InsertEntity(recordEntity);
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
                result.setMessage("本地回写失败");
                result.setStatus(1);
            }
        } catch (Exception ex) {
            String logtxt = "[OutStatusCallback]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }
}
